package com.pupil.down.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: pupil
 * @Date: 2024/09/28 下午 5:15
 */
public class HttpUtil {

    /**
     * 获取 HTTP 链接
     *
     * @param url 文件链接
     * @return
     * @throws IOException
     */
    public static HttpURLConnection getHttpUrlConnection(String url) throws IOException {
        URL httpUrl = new URL(url);
        // 获取httpUrl对象建立一个与指定URL的HTTP连接，并强转未HttpURLConnection类型
        // HttpURLConnection 是 Java 用来发送 HTTP 请求和接收响应的类
        HttpURLConnection httpConnection = (HttpURLConnection) httpUrl.openConnection();
        // 设置请求头，并将请求模仿为浏览器发送的
        // User-Agent 用于告诉服务器，发出请求的客户端的设备类型、操作系统、浏览器等信息
        httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edge/14.14393");
        return httpConnection;
    }


    /**
     * 获取 分片下载的 HTTP 链接
     *
     * @param url   文件链接
     * @param start 开始位置
     * @param end   结束位置
     * @return
     * @throws IOException
     */
    public static HttpURLConnection getHttpUrlConnection(String url, Long start, Long end) throws IOException {
        HttpURLConnection httpUrlConnection = getHttpUrlConnection(url);
        if (start == null) {
            return httpUrlConnection;
        }

        LogUtil.debug("此线程下载内容区间 {}-{}", start, end);
        // 设置请求头Range，用于指定下载文件的字节范围
        if (end != null) {
            httpUrlConnection.setRequestProperty("RANGE", "bytes=" + start + "-" + end);
        } else {
            httpUrlConnection.setRequestProperty("RANGE", "bytes=" + start + "-");
        }

        // 获取响应头信息，键值对的形式存储下来
        Map<String, List<String>> headerFields = httpUrlConnection.getHeaderFields();
        // 通过日志记录该线程的响应头信息
        for (String s : headerFields.keySet()) {
            LogUtil.debug("此线程请求头{}:{}", s, headerFields.get(s));
        }

        return httpUrlConnection;
    }

    /**
     * 获取网络文件大小
     *
     * @param url 文件链接
     * @return
     * @throws IOException
     */
    public static Long getHttpFileContentLength(String url) throws IOException {
        HttpURLConnection httpUrlConnection = getHttpUrlConnection(url);
        // 获取文件大小
        long contentLengthLong = httpUrlConnection.getContentLengthLong();
        // 关闭链接
        httpUrlConnection.disconnect();
        return contentLengthLong;
    }

    /**
     * 获取网络文件名字
     *
     * @param url 文件链接
     * @return
     */
    public static String getHttpFileName(String url) {
        int lastIndexOf = url.lastIndexOf("/");
        String fileName = url.substring(lastIndexOf + 1);
        return fileName;
    }
}
